var map = null; //地图对象
var ctx = window.daijia.ctx;
var dj = window.daijia.dj;
var zhuanche = window.daijia.zhuanche;
var freight = window.daijia.freight;
var kongxian = 0;//空闲
var paidan = 0;//已派单
var manglu = 0;//忙碌
var lixian = 0;//未上班
var workcar = 0;//工作车

var membermarker = null;//客户标记
var driverArr = [];//服务人员标记集合

var mapLoadFinish = false;

var loadLixianDrivers = false;//是否点击了下线服务人员


function initialize(refresh) {

    if (refresh) {
        initData(refresh);
    }
    else {
        var lng = window.daijia.lng;
        var lat = window.daijia.lat;
        var point = new BMap.Point(lng, lat);

        if (point) {
            map = new BMap.Map("allmap");
            map.centerAndZoom(point, 11);
            map.enableScrollWheelZoom();
            map.addControl(new BMap.MapTypeControl({
                anchor: BMAP_ANCHOR_TOP_RIGHT,
                mapTypes: [BMAP_NORMAL_MAP, BMAP_HYBRID_MAP]
            }));

            map.addControl(new BMap.NavigationControl({
                anchor: BMAP_ANCHOR_BOTTOM_RIGHT,
                type: BMAP_NAVIGATION_CONTROL_SMALL
            }));  //右上角，仅包含平移和缩放按钮

            var ctrl = new BMapLib.TrafficControl({
                showPanel: false //是否显示路况提示面板
            });
            map.addControl(ctrl);
            ctrl.setAnchor(BMAP_ANCHOR_TOP_LEFT);


            //地图加载完毕
            map.addEventListener('tilesloaded', function () {

                if (!mapLoadFinish) {

                    mapLoadFinish = true;

                    initData(refresh);

                }
            });

        }
        else {
            $.scojs_message("地区" + center + "位置不准确，请重新编辑地区", $.scojs_message.TYPE_ERROR);
        }
    }

}

function initPanelLeft(drivers) {
    var driverBusyContent = "";
    var driverBusyAmount = 0;
    if (drivers.length > 0) {
        $.each(drivers, function (index, driver) {

            if (driver.status == 2 || driver.status == 3) {
                driverBusyAmount++;

                var status = "";
                if (driver.status == 2) {
                    status = "已派单";
                } else if (driver.status == 3) {
                    status = "已接单";
                    if (null != driver.orderInfo && null != driver.orderInfo.status) {
                        if (driver.orderInfo.status == 4) {
                            status = "执行中";
                        }
                        else if (driver.orderInfo.status == 3) {
                            status = "预约地";
                        }
                    }
                }

                var jobStatus = "";
                if (null != driver.jobStatus) {
                    if (driver.jobStatus == 0) {
                        jobStatus = "代驾";
                    }
                    else if (driver.jobStatus == 1) {
                        jobStatus = "专车";
                    }
                    else if (driver.jobStatus == 2) {
                        if (null == driver.errandType) {
                            jobStatus = "跑腿";
                        } else {
                            jobStatus = driver.errandType;
                        }
                    }
                    else if (driver.jobStatus == 3) {
                        jobStatus = "货运";
                    }
                    else if (driver.jobStatus == 4) {
                        jobStatus = "快车";
                    }
                }
                else {
                    jobStatus = "未知";
                }

                var currentOrder = "";

                if (jobStatus == "代驾" || jobStatus == "专车" || jobStatus == "货运") {
                    if (null != driver.orderInfo) {
                        var fromPlace = driver.orderInfo.fromPlace;
                        var toPlace = driver.orderInfo.toPlace;
                        if (fromPlace.length > 15) {
                            fromPlace = driver.orderInfo.fromPlace.substring(0, 12) + "...";
                        }
                        if (toPlace != null) {
                            if (toPlace.length > 15) {
                                toPlace = driver.orderInfo.toPlace.substring(0, 12) + "...";
                            }
                        } else {
                            toPlace = "";
                        }

                        currentOrder = "<div class='panel-boda' style='display: none;'>" +
                            "<div class='panel-left_sjiao'></div>" +
                            "<div class='panel-left_xq'>" +
                            "<div class='panel-left_icon1'><span><img src='" + ctx + "/assets/img/panel-1.png'/></span><span>" + driver.orderInfo.orderNumber + "</span></div>" +
                            "<div class='panel-left_icon1'><span><img src='" + ctx + "/assets/img/panel-2.png'/></span><span>" + driver.orderInfo.date + "</span></div>" +
                            "<div class='panel-left_icon1'><span><img src='" + ctx + "/assets/img/panel-3.png'/></span><span>" + fromPlace + "</span></div>" +
                            "<div class='panel-left_icon1'><span><img src='" + ctx + "/assets/img/panel-4.png'/></span><span>" + toPlace + "</span></div>" +
                            "</div>" +
                            "</div>";
                    }
                } else if (jobStatus == "快车") {
                    var jobContent = driver.jobContent;
                    if (null != jobContent && jobContent.length > 0) {
                        var jobContentArr = jobContent.split(",");
                        var contentDiv = "";
                        for (var i = 0; i < jobContentArr.length; i++) {
                            if (jobContentArr[i] != "") {
                                contentDiv += "<div class='panel-left_icon1'><span><img src='" + ctx + "/assets/img/panel-1.png'/></span><span>" + jobContentArr[i] + "</span></div>";
                            }
                        }
                        currentOrder = "<div class='panel-boda' style='display: none;'>" +
                            "<div class='panel-left_sjiao'></div>" +
                            "<div class='panel-left_xq'>" +
                            "<div class='panel-left_icon1'><span><img src='" + ctx + "/assets/img/panel-3.png'/></span><span>当前人数：" + driver.seatsNow + " 可乘人数：" + driver.seatsTotal + "</span></div>" +
                            contentDiv +
                            "</div>" +
                            "</div>";
                    }

                } else if (jobStatus == "跑腿" || jobStatus == driver.errandType) {
                    //跑腿
                    var jobContent = driver.jobContent;
                    if (null != jobContent && jobContent.length > 0) {
                        var jobContentArr = jobContent.split(",");
                        var contentDiv = "";
                        for (var i = 0; i < jobContentArr.length; i++) {
                            if (jobContentArr[i] != "") {
                                contentDiv += "<div class='panel-left_icon1'><span><img src='" + ctx + "/assets/img/panel-1.png'/></span><span>" + jobContentArr[i] + "</span></div>";
                            }
                        }
                        currentOrder = "<div class='panel-boda' style='display: none;'>" +
                            "<div class='panel-left_sjiao'></div>" +
                            "<div class='panel-left_xq'>" +
                            contentDiv +
                            "</div>" +
                            "</div>";
                    }
                }

                var errandserviceType = "";
                if (null != driver.errandserviceType) {
                    errandserviceType = "(" + driver.errandserviceType + ")";
                }

                driverBusyContent += "<div class='panel-left_text'><span class='panel-left_text-a'>" + jobStatus + "</span><span>" + status + "</span><span class='panel-left_text-c'>（" + driver.monthOrders + "单）</span><span>" + driver.realname + errandserviceType + "</span>" +
                    currentOrder +
                    "</div>";

            }


        });
    }
    $("#driver-busy-amount").html(driverBusyAmount);
    $("#driver-busy-div").html(driverBusyContent);
}

function addMarker(driver) {

    var detailStatus = '';
    if (!driver.workCar) {
        //如果不是工作车
        if (driver.status == 0) {
            detailStatus = 'lixian';
            lixian++;
        }
        else if (driver.status == 1) {
            detailStatus = 'kongxian';
            kongxian++;
        }
        else if (driver.status == 2) {
            detailStatus = 'paidan';
            paidan++;
        }
        else if (driver.status == 3) {
            detailStatus = 'manglu';
            manglu++;
        }
    }
    else {
        detailStatus = 'workcar';
        workcar++;
    }

    var htm = '';

    if (!driver.workCar) {
        //如果不是工作车
        if (detailStatus == 'kongxian') {
            htm = '<div id="driver_marker_' + driver.id + '" class="sj-mark driver_marker_class" data-z-index="9" style="position:absolute;z-index:9;">' +
                '<div class="sj-mark-ma sjcolor-' + detailStatus + '"><span>' + driver.realname + '</span></div>' +
                '<div class="sj-mark-rk rkcolor-' + detailStatus + '"></div>' +
                '</div>';
        }
        else {
            htm = '<div id="driver_marker_' + driver.id + '" class="sj-mark driver_marker_class" data-z-index="99" style="position:absolute;z-index:99;display:none;">' +
                '<div class="sj-mark-ma sjcolor-' + detailStatus + '"><span>' + driver.realname + '</span></div>' +
                '<div class="sj-mark-rk rkcolor-' + detailStatus + '"></div>' +
                '</div>';
        }
    }
    else {
        htm = '<div id="driver_marker_' + driver.id + '" class="driver_workcar_marker_class" data-z-index="9998" style="position:absolute;z-index:9998;width:110px;display:none;">' +
            '<div class="em-' + detailStatus + '-l"></div>' +
            '<div class="em-' + detailStatus + '-con">' + driver.realname + '</div>' +
            '<div class="em-' + detailStatus + '-r"></div>' +
            '</div>';
    }

    var point = new BMap.Point(driver.longitude, driver.latitude);
    //服务人员标注
    var marker = new BMapLib.RichMarker(htm, point, {"anchor": new BMap.Size(-40, -35), "enableDragging": true});
    marker.driverid = driver.id;
    marker.driverstatus = detailStatus;

    map.addOverlay(marker);


    var photo = ctx + '/assets/img/toux.png';
    if (driver.photo && driver.photo != '') {
        photo = ctx + '/upload/driver/' + driver.photo;
    }

    var content = "<div id='driver_detail_" + driver.id + "' class='panel-ditu' style='z-index:9999;display:none;'>" +
        "<div class='panel-ditu_xq'>" +
        "<div class='panel-ditu_icon1'>" +
        "<span><img src='" + photo + "'/></span>" +
        "</div>" +
        "<div class='panel-ditu_icon2'>" +
        "<div class='panel-ditu-xqtxet'><span><b>公司：</b>" + driver.company.abbreviation + "</span></div>" +
        "<div class='panel-ditu-xqtxet'><span><b>工号：</b>" + driver.username + "</span></div>" +
        "<div class='panel-ditu-xqtxet'><span><b>电话：</b>" + driver.phone + "</span></div>" +
        "<div class='panel-ditu-xqtxet'><span><b>今日</b>(" + driver.todayOrders + "单)&nbsp;<b>本月</b>(" + driver.monthOrders + "单)</span></div>" +
        "<div class='panel-ditu-xqtxet'><span><b>定位时间：</b>" + formatDate(driver.posUpdated) + "</span></div>" +
        "</div>" +
        "</div>" +
        "<div class='panel-ditu_sjiao'></div>" +
        "</div>";


    //服务人员详细
    var infowindow = new BMapLib.RichMarker(content, point, {
        "anchor": new BMap.Size(-126, -205),
        "enableDragging": true
    });
    map.addOverlay(infowindow);

    marker.addEventListener("onmouseover", function (e) {
        infowindow.setPosition(new BMap.Point(marker._position.lng, marker._position.lat));
        $("#driver_detail_" + driver.id + "").show();//显示当前面板
    });
    marker.addEventListener("onmouseout", function (e) {
        $("#driver_detail_" + driver.id + "").hide();//隐藏当前面板
    });
    marker.addEventListener("ondragend", function (e) {
        infowindow.setPosition(new BMap.Point(marker._position.lng, marker._position.lat));
    });

    driverArr.push(marker);

}

function getTuijianDrivers(refresh) {
    if (!refresh) {
        $("#tuijian-driver-div").html("正在为您推荐服务人员...");
    }

    $.ajax({
        url: ctx + '/driver/tuijianDiaoduDrivers',
        type: 'GET',
        async: false,
        dataType: 'json',
        data: {
            'orderId': $("input[name=new-orders]:checked").val(),
            'orderType': $("input[name=new-orders]:checked").attr("data-type")
        },
        success: function (result) {
            if (result && result.length > 0) {
                var tuijianDriversContent = "";
                $(result).each(function (index, driver) {
                    var photo = ctx + '/assets/img/toux.png';
                    if (driver.photo && driver.photo != '') {
                        photo = ctx + '/upload/driver/' + driver.photo;
                    }

                    var paidanText = "派给";
                    if (driver.workCar) {
                        paidanText = "派给(车)";
                    }

                    if (driver.usuallyEmploy) {
                        paidanText += "(荐)";
                    }
                    var orderType = $("input[name=new-orders]:checked").attr("data-type");
                    if ("daijia" == orderType) {
                        orderType = "代驾";
                    } else if ("zhuanche" == orderType) {
                        orderType = "专车";
                    } else {
                        orderType = "未知";
                    }
                    var errandserviceType = "";
                    if (null != driver.errandserviceType) {
                        if (driver.errandserviceType) {
                            if (driver.errandserviceType == "null") {
                                errandserviceType = "";
                            }
                            else {
                                errandserviceType = "(" + driver.errandserviceType + ")";
                            }
                        }
                    }

                    tuijianDriversContent += "<div class='modal-sj-pdan'><button data-id='" + driver.id + "' data-workCar='" + driver.workCar + "' class='paigeita'>" + paidanText + "</button><span>" + driver.realname + errandserviceType + "</span><span>" + driver.distanceStr + "</span><span style='color: red;'>" + driver.monthOrders + "单</span>" +
                        "<div class='panel-bod' style='display: none;'>" +
                        "<div class='panel-right_sjiao'></div>" +
                        "<div class='panel-right_xq'>" +
                        "<div class='panel-right_icon1'>" +
                        "<span><img src='" + photo + "'/></span>" +
                        "</div>" +
                        "<div class='panel-right_icon2'>" +
                        "<div class='panel-right-xq'><span><b>公司：</b>" + driver.company.abbreviation + "</span></div>" +
                        "<div class='panel-right-xq'><span><b>工号：</b>" + driver.username + "</span></div>" +
                        "<div class='panel-right-xq'><span><b>电话：</b>" + driver.phone + "</span></div>" +
                        "<div class='panel-right-xq'><span><b>今日单数：</b>" + driver.todayOrders + "单</span></div>" +
                        "<div class='panel-right-xq'><span><b>本月单数：</b>" + driver.monthOrders + "单</span></div>" +
                        "</div>" +
                        "</div>" +
                        "</div>" +
                        "</div>";
                });
                $("#tuijian-driver-div").html(tuijianDriversContent);

            }
            else {
                $("#tuijian-driver-div").html("没有找到合适的服务人员");
            }

            $("#new-orders-div .panel-zc_not").each(function (index, element) {
                $(element).css("right", $("#new-orders-div").width() + "px");
            });
            $("#tuijian-driver-div .panel-bod").each(function (index, element) {
                $(element).css("right", $("#new-orders-div").width() + "px");
            });

        }
    });
}

function getMarkerByDriverId(driverid, driverstatus) {
    if (driverArr == null || driverArr.length == 0) {
        return null;
    }
    var dm = null;
    $(driverArr).each(function (index, driverMarker) {
        if (driverMarker.driverid == driverid) {
            if (null != driverstatus) {
                driverMarker.driverstatus = driverstatus;
            }
            dm = driverMarker;
            return false;
        }
    });
    return dm;
}

$(document).ajaxSuccess(function (event, xhr, settings) {
    if (settings.url.indexOf("mapmodeDatav3") != -1) {
        setTimeout(function () {
            initialize(true);
        }, 10000);//15s
    }
});
function initData(refresh) {
    $.get(ctx + '/driver/diaodu/mapmodeDatav3?t=' + new Date().getTime() + '', {'loadLixian': loadLixianDrivers}, function (results) {
        var orders = results.orders;
        var drivers = results.drivers;
        var lixianAmounts = results.lixianAmounts;
        var currentCheckedOrderHtm = null;
        var currentMemberPoint = null;
        var orderContent = "";
        var orderAmount = orders.length;
        if (orderAmount > 0) {
            var checkedOrderId = $("input[name=new-orders]:checked").val();
            var checkedOrderType = $("input[name=new-orders]:checked").attr("data-type");
            var hasNewOrders = false;
            var newSet = new Set();
            var orderSet = getSetFromSessionStorage('orderSet');
            $.each(orders, function (index, order) {
                // if(!orderSet.contains(order.id)){
                if(!orderSet.contains(order.id + '')){
                    hasNewOrders = true;
                }
                newSet.add(order.id);
                var type = "";
                if (order.type == "daijia") {
                    type = "代驾";
                }
                else if (order.type == "zhuanche") {
                    type = "专车";
                }
                else if (order.type == "errand") {
                    //type="跑腿";
                    type = order.orderType;
                }
                else if (order.type == "freight") {
                    type = "货运";
                }
                else if (order.type == "zhuanxian") {
                    type = "快车";
                }

                var fromPlace = order.fromPlace;
                var fromPlace2 = order.fromPlace;
                var toPlace = order.toPlace;

                if (order.fromPlace != null) {
                    if (fromPlace.length > 9) {
                        fromPlace = order.fromPlace.substring(0, 7) + "...";
                    }
                    if (fromPlace2.length > 11) {
                        fromPlace2 = order.fromPlace.substring(0, 9) + "...";
                    }
                }
                else {
                    fromPlace = "";
                    fromPlace2 = "";
                }


                if (toPlace != null) {
                    if (toPlace.length > 12) {
                        toPlace = order.toPlace.substring(0, 10) + "...";
                    }
                } else {
                    toPlace = "";
                }


                var carTypeName = "";
                if (null != order.carTypeName) {
                    carTypeName = "(" + order.carTypeName + ")";
                }

                var line_Div = "";
                var seats_Div = ""
                if (order.type == "zhuanxian") {
                    var lineName = "";
                    lineName += "(" + order.orderType + ")";
                    lineName += order.lineName;
                    line_Div = "<div class='panel-left_icon1'><span><img src='" + ctx + "/assets/img/panel-3.png'/></span><span>" + lineName + "</span></div>";

                    seats_Div = "<div class='panel-left_icon1'><span><img src='" + ctx + "/assets/img/panel-4.png'/></span><span>" + order.peopleNumber + "人 </span></div>";
                }


                var currentCheckedOrder = "";
                if (order.id == checkedOrderId && order.type == checkedOrderType) {
                    currentMemberPoint = new BMap.Point(order.clientLongitude, order.clientLatitude);
                    currentCheckedOrderHtm = "<div style='position:absolute;z-index:9999;width:85px;'><img src='" + ctx + "/assets/img/kh.png' /></div>";
                    currentCheckedOrder = "checked='checked'";
                }

                orderContent += "<div class='panel-right_text'>" +
                    "<span class='panel-right_text-b'>" +
                    "<input type='radio' " + currentCheckedOrder + " id='new-orders-" + order.type + "-" + order.id + "' name='new-orders' data-type='" + order.type + "' value='" + order.id + "' data-longitude='" + order.clientLongitude + "' data-latitude='" + order.clientLatitude + "' data-clientName='" + order.clientName + "' />" +
                    "</span>" +
                    "<span>" + order.serverTime + "</span>" +
                    "<span>" + fromPlace + "</span>" +
                    "<span class='panel-right_text-a pull-right'>" + type + "</span>" +

                    "<div class='panel-zc_not' style='display:none;'>" +
                    "<div class='panel-right_zc'>" +
                    "<div class='panel-left_icon1'><span><img src='" + ctx + "/assets/img/panel-1.png'/></span><span>" + order.orderNumber + "</span></div>" +
                    "<div class='panel-left_icon1'><span><img src='" + ctx + "/assets/img/panel-2.png'/></span><span>" + order.serverTime + "</span><span style='color: #E42E00; float: right;'><b>" + carTypeName + "</b></span></div>" +
                    "<div class='panel-left_icon1'><span><img src='" + ctx + "/assets/img/panel-3.png'/></span><span>" + fromPlace2 + "</span></div>" +
                    "<div class='panel-left_icon1'><span><img src='" + ctx + "/assets/img/panel-4.png'/></span><span>" + toPlace + " </span></div>" +
                    line_Div +
                    seats_Div +
                    "</div>" +
                    "</div>" +

                    "</div>";
            });
            newSet.flushToSessionStorage('orderSet');
            if(hasNewOrders) {
                showNotification('新订单','来新订单了，请前往派单吧！',ctx+'/assets/img/logo.png');
                // document.getElementById('new_order_play').play();//播放声音
            }
        }
        $("#new-orders-amount").html(orderAmount);
        $("#new-orders-div").html(orderContent);

        $("#new-orders-div .panel-zc_not").each(function (index, element) {
            $(element).css("right", $("#new-orders-div").width() + "px");
        });

        initPanelLeft(drivers);

        if (refresh) {
            map.clearOverlays();
            driverArr = [];

            kongxian = 0;//空闲
            paidan = 0;//已派单
            manglu = 0;//忙碌
            lixian = 0;//未上班
            workcar = 0;//工作车

            if (null != currentCheckedOrderHtm && null != currentMemberPoint) {
                membermarker = new BMapLib.RichMarker(currentCheckedOrderHtm, currentMemberPoint, {
                    "anchor": new BMap.Size(-20, -46),
                    "enableDragging": true
                });
                map.addOverlay(membermarker);
                if ($("#search_drivers").val() == "") {
                    getTuijianDrivers(refresh);
                }
            }
        }

        if (drivers.length > 0) {
            console.log("drivers:"+drivers.length);
            $.each(drivers, function (index, driver) {
                addMarker(driver);
            });
        }
        console.log("lixianAmounts:"+lixianAmounts);
        lixian = lixianAmounts;
        updateDriverStatusNum();

        if (refresh) {
            //空闲
            if ($("#showkongxian").hasClass("kongxian_active")) {
                showDriversByStatus($("#showkongxian").attr("data-value"));
            }
            else {
                hideDriversByStatus($("#showkongxian").attr("data-value"));
            }

            //已派单
            if ($("#showpaidan").hasClass("pdan_active")) {
                showDriversByStatus($("#showpaidan").attr("data-value"));
            }

            //忙碌
            if ($("#showmanglu").hasClass("manglu_active")) {
                showDriversByStatus($("#showmanglu").attr("data-value"));
            }

            //未上班
            if ($("#showlixian").hasClass("lixian_active")) {
                showDriversByStatus($("#showlixian").attr("data-value"));
            }

            //工作车
            if ($("#showworkcar").hasClass("gzche_active")) {
                showDriversByStatus($("#showworkcar").attr("data-value"));
            }
        }
    });
}

$(document).ready(function () {

    //初始化地图
    initialize(false);
    $(document).on("mouseover", ".panel-left_text", function () {
        var bod = $(this).children("div");
        $(bod).show();
    });

    $(document).on("mouseleave", ".panel-left_text", function () {
        var bod = $(this).children("div");
        $(bod).hide();
    });

    $(document).on("mouseover", ".modal-sj-pdan", function () {
        var bod = $(this).children("div");
        $(bod).show();
    });

    $(document).on("mouseleave", ".modal-sj-pdan", function () {
        var bod = $(this).children("div");
        $(bod).hide();
    });

    $(document).on("mouseover", ".panel-right_text", function () {
        var bod = $(this).children("div");
        $(bod).show();
    });

    $(document).on("mouseleave", ".panel-right_text", function () {
        var bod = $(this).children("div");
        $(bod).hide();
    });


    //选择新单
    $(document).on('click', '.panel-right_text', function () {
        $(this).find("input[name=new-orders]")[0].checked = "checked";
        $("#new-orders-div .panel-right_text").removeClass("panel-right_text_actived");
        $(this).addClass("panel-right_text_actived");

        if (membermarker) {
            membermarker.remove();
        }

        var memberPoint = new BMap.Point($(this).find("input[name=new-orders]").attr("data-longitude"), $(this).find("input[name=new-orders]").attr("data-latitude"));

        var htm = "<div style='position:absolute;z-index:9999;width:85px;'><img src='" + ctx + "/assets/img/kh.png' /></div>";

        membermarker = new BMapLib.RichMarker(htm, memberPoint, {
            "anchor": new BMap.Size(-20, -46),
            "enableDragging": true
        });
        map.addOverlay(membermarker);
        map.centerAndZoom(memberPoint, 11);

        getTuijianDrivers();
    });


//    $(document).on('change','input[name=new-orders]',function(){
//    	
//    	$("#new-orders-div .panel-right_text").removeClass("panel-right_text_actived");
//    	$(this).parent().parent().addClass("panel-right_text_actived");
//    	
//    	if(membermarker){
//    		membermarker.remove();
//    	}
//	
//    	var memberPoint=new BMap.Point($(this).attr("data-longitude"), $(this).attr("data-latitude"));
//  	
//    	var htm = "<div style='position:absolute;z-index:9999;width:85px;'><img src='"+ctx+"/assets/img/kh.png' /></div>";
//
//    	membermarker = new BMapLib.RichMarker(htm, memberPoint, {"anchor": new BMap.Size(-20, -46), "enableDragging": true});
//    	map.addOverlay(membermarker);
//    	map.centerAndZoom(memberPoint, 11);
//    	
//    	getTuijianDrivers();
//    	
//    });

    $(document).on("click", ".paigeita", function () {
        if ($("input[name=new-orders]:checked").length == 0) {
            $.scojs_message("请先选择一个订单", $.scojs_message.TYPE_ERROR);
            return false;
        }

//    	if(window.confirm('确认要派单给该服务人员吗？')){
        var driverId = $(this).attr("data-id");
        var driverIsWork = $(this).attr("data-workCar");
        var orderId = $("input[name=new-orders]:checked").val();
        var orderType = $("input[name=new-orders]:checked").attr("data-type");
        var paidanUrl = "";
        if (orderType == "daijia") {
            paidanUrl = ctx + '/order/diaoduPaidan';
        }
        else if (orderType == "zhuanche") {
            paidanUrl = ctx + '/zhuanche/paidan';
        }
        else if (orderType == "errand") {
            paidanUrl = ctx + '/errand/paidan';
        }
        else if (orderType == "freight") {
            paidanUrl = ctx + "/freight/paidan";
        }
        else if (orderType == "zhuanxian") {
            paidanUrl = ctx + "/zhuanxian/paidan";
        }

        $.post(paidanUrl, {'driverId': driverId, 'orderId': orderId}, function (data) {
            if (data.success) {
                if ($("#new-orders-" + orderType + "-" + orderId + "").length > 0) {

                    var dm = null;

                    if (driverIsWork == "true") {//如果是工作车
                        dm = getMarkerByDriverId(driverId, null);
                    }
                    else {
                        dm = getMarkerByDriverId(driverId, "paidan");
                    }

                    if (null != dm) {
                        $.scojs_message('派单成功', $.scojs_message.TYPE_OK);

                        if (membermarker) {
                            membermarker.remove();
                        }

                        $("#new-orders-" + orderType + "-" + orderId + "").parent().parent().remove();//移除订单
                        $("#tuijian-driver-div").html("");//移除推荐服务人员
                        $.get(ctx + '/driver/diaodu/mapmodeDatav3', {}, function (results) {
                            var drivers = results.drivers;
                            // initPanelLeft(drivers);
                        });

                        if (driverIsWork == "false") {//如果不是工作车
                            var thisdm = $("#driver_marker_" + driverId + "");
                            $(thisdm.find("div")[0]).removeClass("sjcolor-kongxian").addClass("sjcolor-paidan");
                            $(thisdm.find("div")[1]).removeClass("rkcolor-kongxian").addClass("rkcolor-paidan");

                            if ($("#showpaidan").hasClass("pdan_active")) {
                                thisdm.fadeIn(200);
                            }
                            else {
                                thisdm.fadeOut(200);
                            }

                            //更新数量
                            --kongxian;
                            ++paidan;
                            updateDriverStatusNum();
                        }
                    }

                }
            }
            else {
                $.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
            }
        });

//    	}

    });

    $("#search_drivers").keyup(function () {

        var keyword = $(this).val();
        if ($(this).val().length > 0) {
            var val = $('input[name=new-orders]:checked').val();

            if (!val) {
                alert('请先选择未派的订单');
                $('#tuijian-driver-div').val('');
                return false;
            }

            $("#tuijian-driver-div").html("");

            $.get(ctx + "/driver/queryDiaoduDrivers", {
                'orderId': $('input[name=new-orders]:checked').val(),
                'orderType': $('input[name=new-orders]:checked').attr("data-type"),
                'keyword': keyword
            }, function (results) {
                if (results.length > 0) {
                    $(results).each(function (index, data) {

                        console.debug();


                        var photo = ctx + '/assets/img/toux.png';
                        if (data.photo && data.photo != '') {
                            photo = ctx + '/upload/driver/' + data.photo;
                        }

                        var paidanText = "派给";
                        if (data.workCar) {
                            paidanText = "派给(车)";
                        }

                        if (data.usuallyEmploy) {
                            paidanText += "(荐)";
                        }

                        var errandserviceType = "";
                        if (null != data.errandserviceType) {
                            if (data.errandserviceType) {
                                if (data.errandserviceType == "null") {
                                    errandserviceType = "";
                                }
                                else {
                                    errandserviceType = "(" + data.errandserviceType + ")";
                                }
                            }
                        }

                        var tuijianDriversContent = "<div class='modal-sj-pdan'><button data-id='" + data.id + "' data-workCar='" + data.workCar + "' class='paigeita'>" + paidanText + "</button><span>" + data.realname + errandserviceType + "</span><span>" + data.distanceStr + "</span><span style='color: red;'>" + data.monthOrders + "单</span>" +
                            "<div class='panel-bod' style='display: none;'>" +
                            "<div class='panel-right_sjiao'></div>" +
                            "<div class='panel-right_xq'>" +
                            "<div class='panel-right_icon1'>" +
                            "<span><img src='" + photo + "'/></span>" +
                            "</div>" +
                            "<div class='panel-right_icon2'>" +
                            "<div class='panel-right-xq'><span><b>公司：</b>" + data.company.abbreviation + "</span></div>" +
                            "<div class='panel-right-xq'><span><b>工号：</b>" + data.username + "</span></div>" +
                            "<div class='panel-right-xq'><span><b>今日单数：</b>" + data.todayOrders + "单</span></div>" +
                            "<div class='panel-right-xq'><span><b>本月单数：</b>" + data.monthOrders + "单</span></div>" +
                            "</div>" +
                            "</div>" +
                            "</div>" +
                            "</div>";
                        $("#tuijian-driver-div").append(tuijianDriversContent);
                    });
                }
                else {
                    $("#tuijian-driver-div").html("");
                }
            });
        }
        else {
            $("#tuijian-driver-div").html("");
        }

    });

    //左面板
    $("#panelleft").click(function () {
        if ($(".panel-left").is(':hidden')) {
            $(".panel-left").show(300);
        }
        else {
            $(".panel-left").hide(300);
        }
    });

    //右面板
    $("#panelright").click(function () {
        if ($(".panel-right").is(':hidden')) {
            $(".panel-right").show(300);
        }
        else {
            $(".panel-right").hide(300);
        }
    });

    $("#showkongxian").click(function () {//空闲
        if ($(this).hasClass("kongxian_active")) {
            hideDriversByStatus($(this).attr("data-value"));
            $(this).removeClass("kongxian_active");
        }
        else {
            showDriversByStatus($(this).attr("data-value"));
            $(this).addClass("kongxian_active");
        }
    });
    $("#showpaidan").click(function () {//已派单
        if ($(this).hasClass("pdan_active")) {
            hideDriversByStatus($(this).attr("data-value"));
            $(this).removeClass("pdan_active");
        }
        else {
            showDriversByStatus($(this).attr("data-value"));
            $(this).addClass("pdan_active");
        }
    });
    $("#showmanglu").click(function () {//忙碌
        if ($(this).hasClass("manglu_active")) {
            hideDriversByStatus($(this).attr("data-value"));
            $(this).removeClass("manglu_active");
        }
        else {
            showDriversByStatus($(this).attr("data-value"));
            $(this).addClass("manglu_active");
        }
    });

    $("#showlixian").click(function () {//未上班
        if ($(this).hasClass("lixian_active")) {
            loadLixianDrivers = false;
            hideDriversByStatus($(this).attr("data-value"));
            $(this).removeClass("lixian_active");
        }
        else {
            loadLixianDrivers = true;
            $(this).addClass("lixian_active");
            showDriversByStatus($(this).attr("data-value"));
        }
    });

    $("#showworkcar").click(function () {//工作车
        if ($(this).hasClass("gzche_active")) {
            hideDriversByStatus($(this).attr("data-value"));
            $(this).removeClass("gzche_active");
        }
        else {
            showDriversByStatus($(this).attr("data-value"));
            $(this).addClass("gzche_active");
        }
    });
});

function updateDriverStatusNum() {
    $("#kongxianDrivers").html(kongxian);
    $("#paidanDrivers").html(paidan);
    $("#mangluDrivers").html(manglu);
    $("#lixianDrivers").html(lixian);

    $("#workcarDrivers").html(workcar);
}

function showDriversByStatus(status) {
    if (driverArr == null || driverArr.length == 0) {
        return;
    }
    if (null != status) {
        $(driverArr).each(function (index, driverMarker) {
            if (null != driverMarker.driverid && null != driverMarker.driverstatus) {
                if (driverMarker.driverstatus == status) {
                    $("#driver_marker_" + driverMarker.driverid + "").css("z-index", 1000).fadeIn(0);
                }
                else {
                    $("#driver_marker_" + driverMarker.driverid + "").css("z-index", $("#driver_marker_" + driverMarker.driverid + "").attr("data-z-index"));
                }
            }
        });
    }
}

function hideDriversByStatus(status) {
    if (driverArr == null || driverArr.length == 0) {
        return;
    }
    if (null != status) {
        $(driverArr).each(function (index, driverMarker) {
            if (null != driverMarker.driverid && null != driverMarker.driverstatus && driverMarker.driverstatus == status) {
                $("#driver_marker_" + driverMarker.driverid + "").fadeOut(200);
            }
        });
    }
}

function formatDate(times) {
    if (null == times || times == "") {
        return "";
    }
    var now = new Date(times);
    var year = now.getYear();
    var month = now.getMonth() + 1;
    var date = now.getDate();
    var hour = now.getHours();
    var minute = now.getMinutes();
    var second = now.getSeconds();
    return month + "-" + date + "   " + hour + ":" + minute;
}
/**
 * 通过Html调用显示系统通知
 * @param title
 * @param msg
 * @param imgUrl
 */
function showNotification(title,msg,imgUrl){
    var Notification = window.Notification || window.mozNotification || window.webkitNotification;
    // 判断浏览器是否支持桌面通知
    if(Notification){
        Notification.requestPermission(function(result){
            //result 默认值'default'等同于拒绝 'denied' -用户选择了拒绝 'granted' -用户同意启用通知
            if("granted" != result){
                alert('请授权浏览器能够进行通知!');
                return false;
            }else{
                var tag = "sds"+Math.random();
                var notify = new Notification(
                    title,
                    {
                        dir:'auto',
                        lang:'zh-CN',
                        tag:tag,//实例化的notification的id
                        icon:imgUrl,//通知的缩略图,icon 支持ico、png、jpg、jpeg格式
                        title:title, //通知的标题
                        body:msg //通知的具体内容
                    }
                );
                // 定义通知窗口点击函数
                notify.οnclick=function(){
                    //如果通知消息被点击,通知窗口将被激活
                    window.focus();
                };
                // 定义通知错误事件
                notify.onerror = function () {
                    alert("通知错误");
                };
                // 定义通知显示事件 可以设置多少秒之后关闭 也可以不设置关闭
                notify.onshow = function () {
                    document.getElementById('new_order_play').play();//播放声音
                    // 窗口显示3S后关闭
                    // setTimeout(function(){
                    //     notify.close();
                    // },5000);
                };
                // 定义通知关闭事件
                notify.onclose = function () {

                };
            }
        });
    }else{
        // 提示不支持系统通知
        alert('您的浏览器不支持系统通知,建议使用Chrome浏览');
    }
}
